/**
 * 地址管理服务模块
 *
 * 处理地址相关的数据操作逻辑
 */
const { UserAddress } = require("../models");
const { Op } = require('sequelize');

class AddressService {
  static async getAllAddresses(userId = null) {
    //构建查询条件
    const whereClause = {};
    
    //如果提供了userId，添加过滤条件
    if (userId) {
      whereClause.userId = userId;
    }
    
    //获取所有地址（支持userId过滤），从数据库中查询
    const addresses = await UserAddress.findAll({
      where: whereClause,
      order: [
        ["defaultAddress", "DESC"], //默认地址排在最前面
        ["updatedAt", "DESC"], //使用模型属性名而不是数据库字段名
        ["id", "ASC"],
      ],
    });
    return addresses;
  }

  static async getAddressById(addressId) {
    return await UserAddress.findByPk(addressId);
  }

  static async createAddress(addressData) {
    // 如果设置为默认地址，需要先将该用户的其他地址设为非默认
    if (addressData.defaultAddress === 1) {
      await UserAddress.update(
        { defaultAddress: 0},
        { where: { userId: addressData.userId } }
      );
    }
    
    //创建地址
    return await UserAddress.create(addressData);
  }

  static async updateAddress(address) {
    // 如果设置为默认地址，需要先将该用户的其他地址设为非默认
    if (address.defaultAddress === 1) {
      await UserAddress.update(
        { defaultAddress: 0 },
        { where: { userId: address.userId, id: { [Op.ne]: address.id } } }
      );
    }
    
    //更新地址
    const updateData = {
      userId: address.userId,
      receiverName: address.receiverName,
      receiverPhone: address.receiverPhone,
      provinceName: address.provinceName,
      cityName: address.cityName,
      districtName: address.districtName,
      provinceCode: address.provinceCode,
      cityCode: address.cityCode,
      districtCode: address.districtCode,
      detail: address.detail,
      defaultAddress: address.defaultAddress
    };
    
    await UserAddress.update(updateData, { where: { id: address.id } });

    return await UserAddress.findByPk(address.id);
  }

  static async deleteAddressById(id) {
    if(!id) {
      throw new Error("缺少地址ID，无法删除地址");
    }
    
    //删除地址
    await UserAddress.destroy({ where: { id } });
  }
}

module.exports = AddressService;